package com.yf.ability.login.cropwechat.utils;

import com.alibaba.fastjson.JSON;
import com.yf.ability.login.cropwechat.dto.response.AccessRespDTO;
import com.yf.ability.login.cropwechat.dto.response.DetailRespDTO;
import com.yf.ability.login.cropwechat.dto.response.InfoRespDTO;
import com.yf.base.utils.http.HttpClientUtil;

import lombok.extern.log4j.Log4j2;

/**
 * 企业微信登录辅助类
 * @author bool
 * @date 2021/8/3 14:53
 */
@Log4j2
public class CropWechatUtils {


    /**
     * 获取AccessToken
     */
    private static final String ACCESS_URL = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={cropId}&corpsecret={cropSecret}";

    /**
     * 获取用户信息接口
     */
    private static final String INFO_URL = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token={token}&code={code}";

    /**
     * 读取用户详细信息
     */
    private static final String DETAIL_URL = "https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token={token}&userid={userId}";


    /**
     * 通过企业微信code获取完整用户信息
     * @param cropId
     * @param cropSecret
     * @param code
     * @return
     */
    public static DetailRespDTO requestLogin(String cropId, String cropSecret, String code){

        // 获取accessToken
        String token = requestAccess(cropId, cropSecret);

        // 获取基本信息
        InfoRespDTO info = requestInfo(token, code);

        // 转换为登录结果
        DetailRespDTO rest = requestDetail(token, info.getUserId());

        return rest;
    }

    /**
     * 获取用户详细信息
     * @param accessToken
     * @param userId
     * @return
     */
    public static DetailRespDTO requestDetail(String accessToken, String userId){

        // 获取用户信息
        String url = DETAIL_URL
                .replace("{token}", accessToken)
                .replace("{userId}", userId);
        String json = HttpClientUtil.getJson(url, null, null);
        DetailRespDTO rest =  JSON.parseObject(json, DetailRespDTO.class);
        return rest;
    }


    /**
     * 获取用户基本信息/ID
     * @param accessToken
     * @param code
     * @return
     */
    public static InfoRespDTO requestInfo(String accessToken, String code){
        // 获取用户信息
        String url = INFO_URL
                .replace("{token}", accessToken)
                .replace("{code}", code);
        String json = HttpClientUtil.getJson(url, null, null);
        InfoRespDTO rest =  JSON.parseObject(json, InfoRespDTO.class);
        return rest;
    }


    /**
     * 获取accessToken
     * @param cropId
     * @param cropSecret
     * @return
     */
    public static String requestAccess(String cropId, String cropSecret){

        // 构建完整请求URL
        String url = ACCESS_URL
                .replace("{cropId}", cropId)
                .replace("{cropSecret}", cropSecret);

        // 获得返回JSON
        String json = HttpClientUtil.getJson(url, null, null);

        // 转换为登录结果
        AccessRespDTO rest = JSON.parseObject(json, AccessRespDTO.class);

        return rest.getAccessToken();
    }
}
